<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * API2 class for customer (customer)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Api2_Customer_Rest_Customer_V1 extends Mage_Customer_Model_Api2_Customer_Rest
{
    /**
     * Is customer has rights to retrieve/update customer item
     *
     * @param int $customerId
     * @throws Mage_Api2_Exception
     * @return bool
     */
    protected function _isOwner($customerId)
    {
        if ($this->getApiUser()->getUserId() !== $customerId) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return true;
    }

    /**
     * Retrieve information about customer
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        if ($this->_isOwner($this->getRequest()->getParam('id'))) {
            return parent::_retrieve();
        }
    }

    /**
     * Retrieve collection with only current customer instance
     *
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        return parent::_getCollectionForRetrieve()->addAttributeToFilter('entity_id', $this->getApiUser()->getUserId());
    }

    /**
     * Update customer
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
        /** @var $customer Silk_Zgb_Model_Customer */
        $customer = $this->_loadCustomerById($this->getApiUser()->getUserId());

        /** @var $validator Mage_Api2_Model_Resource_Validator_Eav */
        $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));

        //validate and change password
        if (isset($data['new_password'], $data['conformation'], $data['current_password'])) {
            $validate = Mage::helper('core')->validateHash($data['current_password'], $customer->getPasswordHash());
            if ($validate) {
                if (strlen($data['new_password']) < 6 || strlen($data['new_password']) > 20)
                    $this->_critical("请输入6~20位的密码!", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_LENGTH);

                if ($data['new_password'] === $data['conformation'])
                    $customer->setPassword($data['new_password']);
                else
                    $this->_critical("两次输入的密码不相同!", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_NOT_MATCH);
            } else {
                $this->_critical("当前密码不正确！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_NOT_CORRECT);
            }
        }

        if ($mobile = $this->getParam('mobile')) {
            if (preg_match("/^[1][34578][0-9]{9}$/", $mobile))
                $data['email'] = $mobile . '@hahahui.cn';
            else
                $this->_critical("请输入正确的手机号码！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_MOBILE_ERROR);
        } else
            $this->_critical("手机号码不能为空！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_MOBILE_EMPTY);

        if (!$this->getParam('firstname'))
            $this->_critical("用户名不能为空！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_USERNAME_EMPTY);

        if (preg_match('/^\d+$/', $data['firstname'])) {
            $this->_critical("用户名不能为纯数字!", 101001);
        }

        if (!$this->getParam('lastname'))
            $this->_critical("店铺名不能为空！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_STORENAME_EMPTY);

        /** @var Mage_Customer_Model_Resource_Customer_Collection $customerCollection */
        $customerCollection = Mage::getModel('customer/customer')->getCollection();
        $filterCustomer = $customerCollection->addAttributeToFilter('email', array('eq' => $data['email']))
            ->addAttributeToFilter('entity_id', array('neq' => $customer->getId()))
            ->getFirstItem();

        if ($filterCustomer && $filterCustomer->getId()) {
            $this->_critical('当前手机号码已被占用！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_NOT_FOUND);
        }

        $filterCustomer = $customerCollection->addAttributeToFilter('firstname', array('eq' => $this->getParam('firstname')))
            ->addAttributeToFilter('entity_id', array('neq' => $customer->getId()))
            ->getFirstItem();

        if ($filterCustomer && $filterCustomer->getId()) {
            $this->_critical('用户名已经存在！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_NOT_FOUND);
        }

        $data = $validator->filter($data);

        unset($data['website_id']); // website is not allowed to change

        $customer->addData($data);

        try {
            $customer->save();
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        //$token = Mage::getModel('mapi/token')->loadByToken($this->getRequest()->getHeader('Access-Token'));
        /*$result = array(
            'customer_id' => (int)$customer->getId(),
            'firstname' => $customer->getFirstname(),
            'lastname' => $customer->getLastname(),
            //'username' => $customer->getUsername(),
            'mobile' => $customer->getMobile(),
            //'access_token' => $token->getToken(),
            //'access_token_secret' => $token->getTokenSecret()
        );*/

        return array();
    }

    /**
     * Update customers
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _multiUpdate(array $data)
    {
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }
}
